const salt = (new Date).getTime();
const md5 = require('md5');
const Spinner = require('cli-spinner').Spinner;
const request = require('request-promise');
const spinner = new Spinner('查询中... %s');
module.exports = async function query(q, type) {
    const { appid, '秘钥': key } = require('../config.json');
    if(!appid || !key) {
        console.log('请先执行 fyset appid 秘钥');
    }
    spinner.setSpinnerString('|/-\\');
    spinner.start();
    const sign = md5(appid + q + salt +key);
    let from, to;
    switch(type) {
        case 'ze': {
            from = 'zh';
            to = 'en';
            break;
        }
        case 'ez': {
            from = 'en';
            to = 'zh';
            break;
        }
        default: {
            from = 'auto';
            to = 'zh';
            break;
        } 
    } 
    const data= { q, appid, salt, from, to, sign };
    try {
        const res = await request({
            url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
            type: 'GET',
            json: true,
            qs: data
        });
        
        spinner.stop(true);
        if(res.error_code) {
            console.log(`error: [${res.error_code},${res.error_msg}]`);
            console.log('请检查你的appid和秘钥是否正确设置');
        } else {
            console.log(res.trans_result[0].dst);
        }
    } catch(err) {
        spinner.stop(true);
        console.log(`失败了 ${err.message}`)
    }

}